import { ALL_CATEGORIES,NEW_CATEGORY,DELETE_CATEGORY,UPDATE_CATEGORY } from  '../actions/types';

const initialState = {
  categories:[],
  create_result:{},
  selected_category_id:'',
};

export default (state = initialState, action = {}) => {
  switch(action.type) {
    case NEW_CATEGORY:
      state.categories.push(action.result.data);
      return {
        categories:state.categories,
        create_result:action.result.state
      };
    case ALL_CATEGORIES:
      return {
          categories:action.result.data,
          create_result:action.result.state
        };
    case DELETE_CATEGORY:
      var deleted_id = action.result.data ;
      let cats = state.categories ; 
      for (let item = 0 ; item< cats.length; item++) {
        if ((cats[item].id +'') === (deleted_id+'') ){
            state.categories.splice(item, 1); 
            break;
        }
      }
      return {
        categories: state.categories,
      };
    case UPDATE_CATEGORY:
      let data = action.result.data ;
      for (let item = 0 ; item < state.categories.length; item++) {
        if ((state.categories[item].id +'') === (data.id + '') ){
            state.categories[item].title = data.title ; 
            break;
        }
      }
      return {
        categories: state.categories,
      };
    // case SELECTED_CATEGORY_ID:
    //   return Object.assign({}, state, {
    //     selected_category_id: action.id
    //   });
    default: return state;
  }
}

